package com.skyable.auth.config.security.handler;

import com.alibaba.fastjson.JSONObject;
import com.skyable.common.common.ResponseResult;
import com.skyable.common.constants.exception.AuthExcpConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author GaoYuan
 * @date 2019/11/4 16:30
 * @desc 登录失败处理器
 */
@Slf4j
@Component
public class CloudAuthenctiationFailureHandler implements AuthenticationFailureHandler {

	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {
		log.error("user authenticate failure,reason:" + exception);
		response.setHeader("Content-Type", "application/json;charset=utf-8");
		response.getWriter().write(JSONObject.toJSONString(ResponseResult.error(AuthExcpConstants.ERROR_CODE_AUTH_FAILED,AuthExcpConstants.ERROR_MSG_AUTH_FAILED)));
		response.getWriter().flush();
	}
}